package com.oeaide.workflow.aprendizaje;

import java.util.ArrayList;
import java.util.List;

import org.jbpm.JbpmConfiguration;
import org.jbpm.JbpmContext;
import org.jbpm.context.exe.ContextInstance;
import org.jbpm.db.GraphSession;
import org.jbpm.graph.def.ProcessDefinition;
import org.jbpm.graph.exe.ProcessInstance;
import org.jbpm.graph.exe.Token;
import org.jbpm.taskmgmt.exe.TaskInstance;

import com.oeaide.workflow.aprendizaje.beans.RotacionAlumnoBean;
import com.oeaide.workflow.aprendizaje.beans.SolicitudActividadBean;


public class RotarAlumnoProcessManager {
	
	   static JbpmConfiguration jbpmConfiguration = null;
	   static RotarAlumnoProcessManager __instance = null;

	   private RotarAlumnoProcessManager() 
	    {
	        startConfiguration();
	    }

	   public static RotarAlumnoProcessManager getInstance() {
	        if (__instance == null) {
	            __instance = new RotarAlumnoProcessManager();
	        }
	        return __instance;
	    }
	    

	    static void startConfiguration() {
	        jbpmConfiguration = JbpmConfiguration.parseXmlString(
	                "<jbpm-configuration>" +
	                "  <jbpm-context>" +
	                "    <service name='persistence' " +
	                "             factory='org.jbpm.persistence.db.DbPersistenceServiceFactory' />" +
	                "    <service name='tx' " +
	                "	            factory='org.jbpm.tx.TxServiceFactory' />" +
	                "  </jbpm-context>" +
	                "  <string name='resource.hibernate.cfg.xml' " +
	                "          value='hibernate.cfg.xml' />" +
	                "  <string name='resource.business.calendar' " +
	                "          value='org/jbpm/calendar/jbpm.business.calendar.properties' />" +
	                "  <string name='resource.default.modules' " +
	                "          value='org/jbpm/graph/def/jbpm.default.modules.properties' />" +
	                "  <string name='resource.converter' " +
	                "          value='org/jbpm/db/hibernate/jbpm.converter.properties' />" +
	                "  <string name='resource.action.types' " +
	                "          value='org/jbpm/graph/action/action.types.xml' />" +
	                "  <string name='resource.node.types' " +
	                "          value='org/jbpm/graph/node/node.types.xml' />" +
	                "  <string name='resource.varmapping' " +
	                "          value='org/jbpm/context/exe/jbpm.varmapping.xml' />" +
	                "</jbpm-configuration>");
	
	    }
	    
	public void RegistrarRotacion(RotacionAlumnoBean rotacion)
	{
		 
		        JbpmContext jbpmContext = jbpmConfiguration.createJbpmContext();
		        try {
		            GraphSession graphSession = jbpmContext.getGraphSession();
		            ProcessDefinition processDefinition =
		                    graphSession.findLatestProcessDefinition("RealizarRotacion");
		            ProcessInstance processInstance = new ProcessInstance(processDefinition);

		            ContextInstance contextInstance = processInstance.getContextInstance();
		            contextInstance.setVariable("codigoAlumno", rotacion.getCodigoAlumno());
		            contextInstance.setVariable("especialidad", rotacion.getEspecialidad());
		            contextInstance.setVariable("lugarRotacion", rotacion.getLugarRotacion());
		            contextInstance.setVariable("mesRotacion", rotacion.getMesRotacion());
		            contextInstance.setVariable("nivelAcademico", rotacion.getNivelAcademico());
		            contextInstance.setVariable("periodoAcademico", rotacion.getPeriodoAcademico());
		            contextInstance.setVariable("sedeRotacion", rotacion.getSedeRotacion());
		            contextInstance.setVariable("servicioRotacion", rotacion.getServicioRotacion());
		            contextInstance.setVariable("tipoPeriodo", rotacion.getTipoPeriodo());
		            Token token = processInstance.getRootToken();
		            token.signal();
		            token.signal();
		            jbpmContext.save(processInstance);
		        } finally {
		            jbpmContext.close();
		        }
	}

	 public List<RotacionAlumnoBean> RotacionesPendientes()
	 {
	        JbpmContext jbpmContext = jbpmConfiguration.createJbpmContext();
	        List<RotacionAlumnoBean> rotaciones = new ArrayList<RotacionAlumnoBean>();
	        try {
	            GraphSession graphSession = jbpmContext.getGraphSession();
	            ProcessDefinition processDefinition = graphSession.findLatestProcessDefinition("RealizarRotacion");
	            List processInstances = graphSession.findProcessInstances(processDefinition.getId());
	            for (int i = 0; i < processInstances.size(); i++) {
	                ProcessInstance processInstance = (ProcessInstance) processInstances.get(i);
	                ContextInstance contextInstance = processInstance.getContextInstance();
	                System.out.println("ESTADO: " + processInstance.getRootToken().getNode().getName());
	                if (!processInstance.getRootToken().getNode().getName().equals("Fin"))
	                {
	                	RotacionAlumnoBean nuevo = new RotacionAlumnoBean();
	                	nuevo.setCodigoAlumno(contextInstance.getVariable("codigoAlumno").toString());
	                	nuevo.setEspecialidad(contextInstance.getVariable("especialidad").toString());
	                	nuevo.setLugarRotacion(contextInstance.getVariable("lugarRotacion").toString());
	                	nuevo.setMesRotacion(contextInstance.getVariable("mesRotacion").toString());
	                	nuevo.setNivelAcademico(contextInstance.getVariable("nivelAcademico").toString());	
	                	nuevo.setPeriodoAcademico(contextInstance.getVariable("periodoAcademico").toString());
	                	nuevo.setSedeRotacion(contextInstance.getVariable("sedeRotacion").toString());
	                	nuevo.setServicioRotacion(contextInstance.getVariable("servicioRotacion").toString());
	                	nuevo.setTipoPeriodo(contextInstance.getVariable("tipoPeriodo").toString());
	                	rotaciones.add(nuevo);
	                }
	            }
	        }catch(Exception ex)
	        {	
	        	System.out.print(ex.getMessage());
	        } 
	        finally {
	            jbpmContext.close();
	        }
	        return rotaciones;
	    }
	 
	 public void AprobarRotacion(RotacionAlumnoBean rotacion) 
	 {
		 JbpmContext jbpmContext = jbpmConfiguration.createJbpmContext();
	        try {
	            GraphSession graphSession = jbpmContext.getGraphSession();
	            
	            ProcessDefinition processDefinition =
	                    graphSession.findLatestProcessDefinition("RealizarRotacion");
	            List processInstances = graphSession.findProcessInstances(processDefinition.getId());
	            
	            for (int i = 0; i < processInstances.size(); i++) 
	            {
	                ProcessInstance processInstance = (ProcessInstance) processInstances.get(i);
	                ContextInstance contextInstance = processInstance.getContextInstance();
	                
	                if (rotacion.getId().equals(String.valueOf(processInstance.getId())))
	                {
	                	List<TaskInstance> tasks=jbpmContext.getTaskMgmtSession().findTaskInstancesByProcessInstance(processInstance);
	                	for(TaskInstance ti : tasks){
	            			System.out.println("TaskInstance ID: "+ti.getId()+" - Name: "+ti.getName()+ " - Creada: " +ti.getCreate());
	            		}
	                	
	            		if(tasks.size() > 0)
	            		{
	            			System.out.println("ESTADO: " + processInstance.getRootToken().getNode().getName());
	            			TaskInstance elegirTarea=tasks.get(1);
	            			System.out.println("Encontre una tarea = "+elegirTarea.getName());
	            			elegirTarea.start();
	            			System.out.println("la variable Aprueba tiene el valor = "+elegirTarea.getVariable("aprobar"));
	            			elegirTarea.setVariable("aprobar", "aprueba");
	            			System.out.println("la variable Aprueba tiene el valor = "+elegirTarea.getVariable("aprobar"));
	            			elegirTarea.end();
	            			
	            			
	            			Token token = processInstance.getRootToken();
	    		            token.signal();
	    		            
	            		  }
	            		
	   		    
	                }
	                jbpmContext.save(processInstance);
	            }
	            
        	
	            
	        }catch(Exception ex)
	        {	
	        	System.out.print(ex.getMessage());
	        } 
	        finally 
	        {
	            jbpmContext.close();
	        
	      
	        }
	 }
	 
}
